import 'package:flutter/material.dart';
import '../services/coffee_service.dart';
import '../model/Coffee.dart';

class QuickTestPage extends StatefulWidget {
  @override
  _QuickTestPageState createState() => _QuickTestPageState();
}

class _QuickTestPageState extends State<QuickTestPage> {
  final CoffeeService _coffeeService = CoffeeService();
  List<Coffee> _coffees = [];
  bool _isLoading = false;
  String _status = '准备测试...';

  Future<void> _testApi() async {
    setState(() {
      _isLoading = true;
      _status = '正在连接 API...';
      _coffees = [];
    });

    try {
      _status = '获取咖啡数据中...';
      final coffees = await _coffeeService.getAllCoffees();

      setState(() {
        _coffees = coffees;
        _status = '成功获取 ${coffees.length} 个咖啡';
      });
    } catch (e) {
      setState(() {
        _status = '连接失败: $e\n使用模拟数据继续测试';
      });
      // 使用模拟数据继续测试UI
      await _testWithMockData();
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _testWithMockData() async {
    final mockCoffees = [
      Coffee(
        name: "测试拿铁",
        price: "28",
        imagePath: "assets/test.png",
        rating: "4.5",
      ),
      Coffee(
        name: "测试美式",
        price: "25",
        imagePath: "assets/test.png",
        rating: "4.3",
      ),
    ];

    setState(() {
      _coffees = mockCoffees;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('API 快速测试'), backgroundColor: Colors.blue),
      body: Padding(
        padding: EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 状态显示
            Card(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '测试状态:',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    SizedBox(height: 8),
                    Text(
                      _status,
                      style: TextStyle(
                        color: _status.contains('成功')
                            ? Colors.green
                            : _status.contains('失败')
                            ? Colors.red
                            : Colors.orange,
                      ),
                    ),
                  ],
                ),
              ),
            ),

            SizedBox(height: 20),

            // 测试按钮
            Center(
              child: ElevatedButton.icon(
                onPressed: _isLoading ? null : _testApi,
                icon: _isLoading
                    ? CircularProgressIndicator(
                        color: Colors.white,
                        strokeWidth: 2,
                      )
                    : Icon(Icons.play_arrow),
                label: Text(_isLoading ? '测试中...' : '开始测试'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.green,
                  foregroundColor: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                ),
              ),
            ),

            SizedBox(height: 20),

            // 结果显示
            if (_coffees.isNotEmpty) ...[
              Text(
                '获取到的咖啡数据:',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
              ),
              SizedBox(height: 10),
              Expanded(
                child: ListView.builder(
                  itemCount: _coffees.length,
                  itemBuilder: (context, index) {
                    final coffee = _coffees[index];
                    return Card(
                      margin: EdgeInsets.only(bottom: 8),
                      child: ListTile(
                        leading: CircleAvatar(
                          backgroundColor: Colors.grey[200],
                          child: Text((index + 1).toString()),
                        ),
                        title: Text(coffee.name),
                        subtitle: Text('¥${coffee.price} ⭐${coffee.rating}'),
                        trailing: Icon(Icons.coffee, color: Colors.brown),
                      ),
                    );
                  },
                ),
              ),
            ] else if (!_isLoading) ...[
              Center(
                child: Column(
                  children: [
                    Icon(Icons.coffee, size: 64, color: Colors.grey[300]),
                    SizedBox(height: 16),
                    Text('暂无数据', style: TextStyle(color: Colors.grey)),
                    Text('点击上方按钮测试API', style: TextStyle(color: Colors.grey)),
                  ],
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
